<?php

/**
 * @Project NUKEVIET 3.0
 * @Author VINADES.,JSC (contact@vinades.vn)
 * @Copyright (C) 2010 VINADES., JSC. All rights reserved
 * @Createdate 3-6-2010 0:30
 */
if (!defined('NV_IS_MOD_DOWNLOAD'))
    die('Stop!!!');

global $global_config, $lang_module, $lang_global, $module_info, $module_name, $module_file, $nv_Request;
$download_config = initial_config_data();

$page_title = $lang_module['search'];
$xtpl = new XTemplate("search_result.tpl", NV_ROOTDIR . "/themes/" . $module_info['template'] . "/modules/" . $module_file . "/");
$xtpl->assign('LANG', $lang_module);

$xtpl->assign('SEARCHTITLE', $lang_module['search_result']);

$page = $nv_Request->get_int('page', 'get', 0);
// came from menu
$cp_mark = $nv_Request->get_string('f', 'get','');

$cat = $nv_Request->get_int('cat', 'post');
$key = filter_text_input( 'q', 'post', '', 1, NV_MAX_SEARCH_LENGTH );
$keyword = $key;
$xtpl->assign("KEYWORD", $key);
$per_page = $download_config['items_per_page'];
$base_url = NV_BASE_SITEURL . "?" . NV_LANG_VARIABLE . "=" . NV_LANG_DATA . "&amp;" . NV_NAME_VARIABLE . "=" . $module_name . "&amp;" . NV_OP_VARIABLE . "=newsearch";

$xtpl->assign('FORMACTION', $base_url);
if($cp_mark){
    if (!$nv_Request->isset_request('submit', 'post')) {
        $base_url .= "&amp;f=m";
    }
}

$query = "SELECT `id`, `title`, `alias`, `parentid` FROM `" . NV_PREFIXLANG . "_" . $module_name . "_categories` WHERE parentid=0 AND `status`=1 ORDER BY weight";
$result = $db->sql_query($query);
$store_cats = array();

$nv_list_cats = nv_listcats(0);
foreach ( $nv_list_cats as $cat_i )
{
    if(!$cat_i['status']){
        continue;
    }
    if($cat == $cat_i['id'] ){
        $cat_i['selected'] = "selected=\"selected\"";
    }
    $xtpl->assign( 'LISTCATS', $cat_i );
    $xtpl->parse( 'main.form.catid' );
    $store_cats[$cat_i['id']] = $cat_i['title'];
}

$xtpl->parse("main.form");
if ($nv_Request->isset_request('submit', 'post')) {

    $key = filter_text_input('q', 'post', '', 1, NV_MAX_SEARCH_LENGTH);
    if(!empty($key)){
        $keyword = $lang_module['with_keyword'] . "&quot;".$key."&quot;";
        $keyword = BoldKeywordInStr($keyword, $key, 'OR');
    }
    else{
        $keyword = "&quot;&quot;";
    }
    $cat = $nv_Request->get_int('cat', 'post');

    foreach($store_cats as $cat_id=>$cat_title){
        if($cat_id == $cat){
            $keyword .= $lang_module['with_cat'] . " ".$cat_title;
        }
    }
    
    if (!empty($cat)) {
        $allcat = " AND `catid`=". $cat;
    } else {
        $allcat = '';
    }
    $search_fields = array(
        'title', 'description',
        'author_name', 'copyright',
        'introtext'
    );
    $where_conditions = array();
    foreach ($search_fields as $field) {
        $where_conditions[] = " (`" . $field . "` LIKE '%" . $key . "%') ";
    }
    if (count($where_conditions) <= 1) {
        $where = $where_conditions[0];
    } else {
        $where = join(" OR ", $where_conditions);
    }
    $sql1 = "SELECT SQL_CALC_FOUND_ROWS * FROM `" . NV_PREFIXLANG . "_" . $module_data . "` WHERE (" . $where .") ". $allcat . " AND `status`=1";
    $sql2 = "SELECT * FROM `" . NV_PREFIXLANG . "_" . $module_data . "` WHERE (" . $where .") ". $allcat . " AND `status`=1 ORDER BY `uploadtime` DESC LIMIT " . $page . ", " . $per_page;
} else {
    $sql1 = "SELECT SQL_CALC_FOUND_ROWS * FROM `" . NV_PREFIXLANG . "_" . $module_data . "` WHERE `status`=1";
    //$sql1 = "SELECT * FROM `" . NV_PREFIXLANG . "_" . $module_data . "` WHERE (" . $where .") ". $allcat . " AND `status`=1";
    $sql2 = "SELECT * FROM `" . NV_PREFIXLANG . "_" . $module_data . "` WHERE `status`=1 ORDER BY `uploadtime` DESC LIMIT " . $page . ", " . $per_page;
}
$result = $db->sql_query($sql1);
$query = $db->sql_query( "SELECT FOUND_ROWS()" );
list( $all_page ) = $db->sql_fetchrow( $query );

//list( $all_page ) = $db->sql_fetchrow($result);
if (!empty($all_page)) {
   
    $result = $db->sql_query($sql2);
    $imageinfo = array();
    $session_files = array();
        $session_files['fileupload'] = array();
        $session_files['linkdirect'] = array();

        $count = 0;
    while ($row = $db->sql_fetchrow($result)) {
        $count ++;
        list( $catalias ) = $db->sql_fetchrow($db->sql_query("SELECT alias FROM `" . NV_PREFIXLANG . "_" . $module_data . "_categories` WHERE id=" . $row['catid'] . ""));
        $row['filesize'] = !empty($row['filesize']) ? nv_convertfromBytes($row['filesize']) : "";
        $row['view_hits'] = (int) $row['view_hits'];
        $row['download_hits'] = (int) $row['download_hits'];
        $row['more_link'] = NV_BASE_SITEURL . "index.php?" . NV_NAME_VARIABLE . "=" . $module_name . "&" . NV_OP_VARIABLE . "=" . $catalias . '/' . $row['alias'];
        $row['uploadtime'] = (int) $row['uploadtime'];
        $list_cats = nv_list_cats(true);
        if(!empty($list_cats[$row['catid']])){
            $row['is_download_allow'] = $list_cats[$row['catid']]['is_download_allow'];
        }
        else{
            $row['is_download_allow'] = 0;
        }
        
        if ($row['is_download_allow']) {
            if (!empty($row['fileupload'])) {
                $fileupload = explode("[NV]", $row['fileupload']);
                $row['fileupload'] = array();

                $a = 1;
                $count_file = count($fileupload);
                foreach ($fileupload as $file) {
                    if (!empty($file)) {
                        $file2 = substr($file, strlen(NV_BASE_SITEURL));
                        $filealias = basename($file2);
                        if (file_exists(NV_ROOTDIR . '/' . $file2) and ( $filesize = filesize(NV_ROOTDIR . '/' . $file2) ) != 0) {
                            $new_name = str_replace("-", "_", $filealias) . ( $count_file > 1 ? "_part" . str_pad($a, 2, '0', STR_PAD_LEFT) : "" );
                            $row['fileupload'][] = array(//
                                'link' => NV_BASE_SITEURL . "files/" . $new_name, 'title' => $new_name
                            );
                            $session_files['fileupload'][$new_name] = array(
                                'src' => NV_ROOTDIR . '/' . $file2, 'id' => $row['id']
                            );

                            $a++;
                        }
                    }
                }
            } else {
                $row['fileupload'] = array();
            }

            if (!empty($row['linkdirect'])) {
                $linkdirect = explode("[NV]", $row['linkdirect']);
                $row['linkdirect'] = array();

                foreach ($linkdirect as $links) {
                    if (!empty($links)) {
                        $links = explode("<br />", $links);

                        $host = "";
                        $scheme = "";

                        foreach ($links as $link) {
                            if (!empty($link) and nv_is_url($link)) {
                                if (empty($host)) {
                                    $host = @parse_url($link);
                                    $scheme = $host['scheme'];
                                    $host = $host['host'];
                                    $host = preg_replace("/^www\./", "", $host);

                                    $row['linkdirect'][$host] = array();
                                }

                                $code = md5($link);
                                $row['linkdirect'][$host][] = array(
                                    'link' => $link, 'code' => $code, 'name' => strlen($link) > 70 ? $scheme . "://" . $host . "..." . substr($link, - ( 70 - strlen($scheme . "://" . $host) )) : $link  //
);
                                $session_files['linkdirect'][$code] = array(
                                    'link' => $link, 'id' => $row['id']
                                );
                            }
                        }
                    }
                }
            } else {
                $row['linkdirect'] = array();
            }

            $row['download_info'] = "";
        } else {
            $row['fileupload'] = array();
            $row['linkdirect'] = array();
            $session_files = array();
            if(!empty($list_cats[$row['catid']])){
                if ($list_cats[$row['catid']]['who_download'] == 2) {
                    $row['download_info'] = $lang_module['download_not_allow_info2'];
                } else {
                    $row['download_info'] = sprintf($lang_module['download_not_allow_info1'], NV_BASE_SITEURL . "index.php?" . NV_LANG_VARIABLE . "=" . NV_LANG_DATA . "&amp;" . NV_NAME_VARIABLE . "=users", NV_BASE_SITEURL . "index.php?" . NV_LANG_VARIABLE . "=" . NV_LANG_DATA . "&amp;" . NV_NAME_VARIABLE . "=users&amp;" . NV_OP_VARIABLE . "=register");
                }
            }
        }
        
        if ($row['is_download_allow']) {
            if (!empty($row['fileupload'])) {
                $xtpl->assign('SITE_NAME', $global_config['site_name']);
                $a = 0;
                foreach ($row['fileupload'] as $fileupload) {
                    $fileupload['key'] = $a;
                    $xtpl->assign('FILEUPLOAD', $fileupload);
                    $xtpl->parse('main.items.download_allow.fileupload.row');
                    $a++;
                }

                $xtpl->parse('main.items.download_allow.fileupload');
            }

            if (!empty($row['linkdirect'])) {
                foreach ($row['linkdirect'] as $host => $linkdirect) {
                    $xtpl->assign('HOST', $host);

                    foreach ($linkdirect as $link) {
                        $xtpl->assign('LINKDIRECT', $link);
                        $xtpl->parse('main.items.download_allow.linkdirect.row');
                    }

                    $xtpl->parse('main.items.download_allow.linkdirect');
                }
            }

            $xtpl->parse('main.items.download_allow');
        } else {
            $xtpl->parse('main.items.download_not_allow');
        }
        $today = mktime(0, 0, 0, date("n"), date("j"), date("Y"));
        $yesterday = $today - 86400;
        if ($row['uploadtime'] >= $today) {
            $row['uploadtime'] = $lang_module['today'] . ": " . date("H:i", $row['uploadtime']);
        } elseif ($row['uploadtime'] >= $yesterday) {
            $row['uploadtime'] = $lang_module['yesterday'] . ": " . date("H:i", $row['uploadtime']);
        } else {
            $row['uploadtime'] = nv_date("d/m/Y H:i", $row['uploadtime']);
        }
        $row['title2'] = $row['title'];
        if(!empty($key)){
            $row['title'] = BoldKeywordInStr($row['title'], $key, "OR");
            $row['introtext'] = BoldKeywordInStr($row['introtext'], $key, "OR");
            $row['description'] = BoldKeywordInStr($row['description'], $key, "OR");
        }
        $icon_link = NV_BASE_SITEURL."themes/" . $module_info['template']."/images/download/download.png";
        $row['icon'] = $icon_link;
        $xtpl->assign('CONTENT', $row);
        if (!empty($row['fileimage'])) {
            $imageinfo['src'] = $row['fileimage'];
        }
        else{
            $imageinfo['src'] = NV_BASE_SITEURL."themes/" . $module_info['template']."/images/download/noimage.gif";
        }
        $xtpl->assign('FILEIMAGE', $imageinfo);
            $xtpl->parse('main.row.is_image');
        $xtpl->parse('main.items.image');
        $xtpl->parse('main.items');
    }
if(!$cp_mark){
    $xtpl->assign("KEYWORD", $keyword);
    $xtpl->assign("SEARCH_RESULT_NUM", $all_page." ".$lang_module['results']);
    $xtpl->parse("main.search_notice");
}
else{
    $xtpl->assign("SEARCH_RESULT_NUM", $all_page. " ". $lang_module['document']);
    $xtpl->parse("main.notice");
}

$session_files = serialize( $session_files );
$nv_Request->set_Session( 'session_files', $session_files );
$generate_page = nv_generate_page($base_url, $all_page, $per_page, $page);
if (!empty($generate_page)) {
        $xtpl->assign('GENERATE_PAGE', $generate_page);
        $xtpl->parse('main.generate_page');
    }
} else {
    $xtpl->assign('GENERATE_PAGE', $lang_module['search_noresult']);
    $xtpl->parse('main.generate_page');
}

$xtpl->parse('main');
$contents = $xtpl->text('main');

include ( NV_ROOTDIR . "/includes/header.php" );
echo nv_site_theme($contents);
include ( NV_ROOTDIR . "/includes/footer.php" );
?>